package com.ybbase.framework.config.shiro;

//import com.ybbase.framework.model.po.system.Permission;
//import com.ybbase.framework.service.system.RoleService;
//import com.ybbase.framework.service.system.UserService;
import com.ybbase.framework.common.constant.ConfigConstant;
import com.ybbase.framework.model.po.system.Organization;
import com.ybbase.framework.model.po.system.Permission;
import com.ybbase.framework.model.po.system.Role;
import com.ybbase.framework.model.po.system.User;
import com.ybbase.framework.service.system.OrganizationService;
import com.ybbase.framework.service.system.PermissionService;
import com.ybbase.framework.service.system.RoleService;
import com.ybbase.framework.service.system.UserService;
import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.ArrayList;
import java.util.List;

/**
 * 自定义身份认证
 * 基于HMAC（ 散列消息认证码）的控制域
 */

public class JWTShiroRealm extends AuthorizingRealm {

    private static Logger LOGGER = LogManager.getLogger(JWTShiroRealm.class);
    protected UserService userService;
    @Autowired
    private RoleService roleService;
    @Autowired
    private PermissionService permissionService;
    @Autowired
    private OrganizationService organizationService;

    public JWTShiroRealm(UserService userService) {
        this.userService = userService;
        this.setCredentialsMatcher(new JWTCredentialsMatcher());
    }

    @Override
    public boolean supports(AuthenticationToken token) {
        return token instanceof JWTToken;
    }

    /**
     * 认证信息.(身份验证) : Authentication 是用来验证用户身份
     * 默认使用此方法进行用户名正确与否验证，错误抛出异常即可。
     */
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authcToken) throws AuthenticationException {
        JWTToken jwtToken = (JWTToken) authcToken;
        String token = jwtToken.getToken();
        User user = null;
        try {
            user = userService.getById(JwtUtils.getUserId(token));
            List<Organization> list = organizationService.getOrgListByUserId(user.getId());
            if (list!=null&&!list.isEmpty()){
                user.setOrganId(list.get(0).getId());
            }
        } catch (Exception e) {
            e.printStackTrace();
            throw new AuthenticationException("获取用户信息失败，请重新登录");
        }
        if (user == null) {
            throw new AuthenticationException("token过期，请重新登录");
        }
        SimpleAuthenticationInfo authenticationInfo = new SimpleAuthenticationInfo(user, ConfigConstant.TOKEN_SALT, ConfigConstant.JWT_REALM);
        return authenticationInfo;
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {
        SimpleAuthorizationInfo simpleAuthorizationInfo = new SimpleAuthorizationInfo();
       User user = (User) principals.getPrimaryPrincipal();
       List<String> roles = new ArrayList<>();
       List<String> rights = new ArrayList<>();
       List<Role> sysRoleList = new ArrayList<>();
       List<Permission> rightList = new ArrayList<>();
       if (user.getRoleList() != null && user.getRoleList().size() > 0) {
           sysRoleList = user.getRoleList();
       } else {
           try {
               sysRoleList = roleService.getRoleListByUserId(Integer.parseInt(user.getId() + ""));
           } catch (Exception e) {
               LOGGER.error(e.getMessage());
               e.printStackTrace();
           }
       }
       String roleIds = "";
       for (Role role : sysRoleList) {
           roles.add(role.getId() + "");
           roleIds = "'" + role.getId() + "',";
       }
       if (roles != null) {
           simpleAuthorizationInfo.addRoles(roles);
       }
       if (!"".equals(roleIds)) {
           try {
               rightList = permissionService.getPermissionInRoleIds(roleIds);
           } catch (Exception e) {
               LOGGER.error(e.getMessage());
               e.printStackTrace();
           }
       }
       if (rightList.size() > 0) {
           rightList.forEach(right -> rights.add(right.getId() + ""));
           simpleAuthorizationInfo.addStringPermissions(rights);
       }
        return simpleAuthorizationInfo;
    }
}
